$(document).ready(function() {
    // 发起异步请求，获取考试记录
    $.ajax({
        url: '/student/getExamRecords',  // 获取考试记录的后端接口
        method: 'GET',
        success: function(response) {
            if (response.code === 200) {
                var examRecords = response.data;  // 获取返回的考试记录数据
                var tableBody = $('#examRecordsTable tbody');
                tableBody.empty();  // 清空表格数据

                // 循环填充考试记录
                examRecords.forEach(function(record) {
                    var recordRow = `
                            <tr>
                                <td>${record.exam.title}</td>
                                <td>${record.exam.teacherName}</td>
                                <td>${record.exam.questionCount * record.exam.scorePerQuestion}</td>
                                <td>${record.totalScore}</td>
                                <td>${record.submittedAt}</td>
                                <td>
                                    <!-- 操作栏：查看试题解析按钮 -->
                                    <button class="btn btn-info btn-sm viewSolutionBtn" data-record-id="${record.recordId}">查看试题解析</button>
                                </td>
                            </tr>
                        `;
                    tableBody.append(recordRow);
                });

                // 绑定查看试题解析按钮的点击事件
                $('.viewSolutionBtn').on('click', function() {
                    var recordId = $(this).data('record-id');  // 获取考试记录的ID
                    fetchSolution(recordId);  // 发起请求获取试题解析
                });
            } else {
                alert('获取考试记录失败');
            }
        },
        error: function() {
            alert('获取考试记录失败');
        }
    });

    function fetchSolution(recordId) {
        $.ajax({
            url: '/student/getExamSolution',  // 获取试题解析的后端接口
            method: 'GET',
            data: { recordId: recordId },  // 传递考试记录ID
            success: function(response) {
                if (response.code === 200) {
                    var solution = response.data;  // 获取试题解析数据
                    console.log(solution);

                    // 填充解析内容
                    $('#examTitle').text(solution.exam.title);  // 试卷标题
                    $('#teacherName').text(solution.exam.teacherName);  // 出卷人
                    $('#totalScore').text(solution.totalScore);  // 我的得分
                    // 假设你已经从服务器获得了试卷信息
                    $('#scorePerQuestion').text(solution.exam.scorePerQuestion);  // 填充每题分数

                    var questionsList = $('#questionsList');
                    questionsList.empty();  // 清空原有解析内容

                    // 循环遍历所有题目并显示解析
                    solution.exam.questions.forEach(function(question, index) {
                        // 判断是否正确（通过 answer.score 判断）
                        var questionClass = question.answer.score === 0 ? 'text-danger' : 'text-success';  // 错题显示红色，正确题目显示绿色
                        var studentAnswerClass = question.answer.score === 0 ? 'text-danger' : 'text-success';  // 我的答案类名
                        var questionText = `<p class="mb-2 ${questionClass}"><strong>问题 ${index + 1}：</strong> ${question.questionText}</p>`;
                        // 正确选项
                        // question.correctOption
                        // 选项HTML，固定四个选项
                        // 选项HTML，固定四个选项
                        var optionsHtml = `
                            <p class="${question.answer.selectedOption === 'A' && question.answer.selectedOption !== question.correctOption ? 'text-danger' : (question.answer.selectedOption === 'A' ? 'text-success' : '')}">A. ${question.optionA}</p>
                            <p class="${question.answer.selectedOption === 'B' && question.answer.selectedOption !== question.correctOption ? 'text-danger' : (question.answer.selectedOption === 'B' ? 'text-success' : '')}">B. ${question.optionB}</p>
                            <p class="${question.answer.selectedOption === 'C' && question.answer.selectedOption !== question.correctOption ? 'text-danger' : (question.answer.selectedOption === 'C' ? 'text-success' : '')}">C. ${question.optionC}</p>
                            <p class="${question.answer.selectedOption === 'D' && question.answer.selectedOption !== question.correctOption ? 'text-danger' : (question.answer.selectedOption === 'D' ? 'text-success' : '')}">D. ${question.optionD}</p>
                        `;


                        // 错误的题目下方显示正确答案
                        var correctAnswer = `<p class="text-primary"><strong>正确答案：</strong>${question.correctOption}</p>`;

                        var questionHtml = `
                        <div class="mb-4">
                            ${questionText}
                            ${optionsHtml}
                            ${correctAnswer}
                        </div>
                    `;

                        questionsList.append(questionHtml);
                    });

                    // 显示模态框
                    var solutionModal = new bootstrap.Modal(document.getElementById('solutionModal'));
                    solutionModal.show();
                } else {
                    alert('获取试题解析失败');
                }
            },
            error: function() {
                alert('获取试题解析失败');
            }
        });
    }
});
